package com.hucc.api.util;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;

/**
 * @author huguocai
 */
public class HttpUtil {
	private static final int timeout = 10000;

	public static String sendGetHttp(String url, int retry, int sleepTime) {
		for (int i = 0; i < retry; i++) {
			if (i > 0) {
				try {
					Thread.sleep(sleepTime);
				} catch (InterruptedException e) {
				}
			}

			String result = HttpUtil.get(url);
			if (result != null && !result.isEmpty()) {
				return result;
			}
		}
		return null;
	}

	public static String get(String httpurl) {
	    HttpURLConnection connection = null;
	    InputStream is = null;
	    BufferedReader br = null;
	    String result = null;// 返回结果字符串
	    try {
	        // 创建远程url连接对象
	        URL url = new URL(httpurl);
	        // 通过远程url连接对象打开一个连接，强转成httpURLConnection类
	        connection = (HttpURLConnection) url.openConnection();
	        // 设置连接方式：get
	        connection.setRequestMethod("GET");
	        // 设置连接主机服务器的超时时间
	        connection.setConnectTimeout(timeout);
	        // 设置读取远程返回的数据时间
	        connection.setReadTimeout(timeout);
	        // 发送请求
	        connection.connect();
	        // 通过connection连接，获取输入流
	        if (connection.getResponseCode() == 200) {
	            is = connection.getInputStream();
	            // 封装输入流is，并指定字符集
	            br = new BufferedReader(new InputStreamReader(is, "UTF-8"));
	            // 存放数据
	            StringBuffer sbf = new StringBuffer();
	            String temp = null;
	            while ((temp = br.readLine()) != null) {
	                sbf.append(temp);
	                sbf.append("\r\n");
	            }
	            result = sbf.toString();
	        } else {
				throw new RuntimeException(String.format("HttpUtil get fail, url: %s ResponseCode: %s", httpurl, connection.getResponseCode()));
			}
	    } catch (Exception e) {
	        throw new RuntimeException(e);
	    } finally {
	        // 关闭资源
	        if (null != br) {
	            try {
	                br.close();
	            } catch (IOException e) {
	                e.printStackTrace();
	            }
	        }

	        if (null != is) {
	            try {
	                is.close();
	            } catch (IOException e) {
	                e.printStackTrace();
	            }
	        }

	        connection.disconnect();// 关闭远程连接
	    }

	    return result;
	}

	public static String post(String httpurl, String jsonStr) {
		OutputStreamWriter out = null;
		BufferedReader in = null;
		String result = null;
		HttpURLConnection conn = null;
		try{
			URL url = new URL(httpurl);
			conn = (HttpURLConnection) url.openConnection();
			conn.setRequestMethod("POST");
			//发送POST请求必须设置为true
			conn.setDoOutput(true);
			conn.setDoInput(true);
			//设置连接超时时间和读取超时时间
			conn.setConnectTimeout(timeout);
			conn.setReadTimeout(timeout);
			conn.setRequestProperty("Content-Type", "application/json");
			conn.setRequestProperty("Accept", "application/json");
			//获取输出流
			out = new OutputStreamWriter(conn.getOutputStream());

			out.write(jsonStr);
			out.flush();
			out.close();
			//取得输入流，并使用Reader读取
			if (200 == conn.getResponseCode()){
				in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));
				StringBuilder sb = new StringBuilder();
				String line;
				while ((line = in.readLine()) != null){
					sb.append(line);
				}
				result = sb.toString();
			} else{
				throw new RuntimeException(String.format("HttpUtil post fail, url: %s ResponseCode: %s", httpurl, conn.getResponseCode()));
			}
		} catch (Exception e){
			throw new RuntimeException(e);
		} finally {
			try{
				if(out != null){
					out.close();
				}
				if(in != null){
					in.close();
				}
			}catch (IOException ioe){
				ioe.printStackTrace();
			}
		}
		return result;
	}

}

